"""
历史数据管理器
"""
from typing import Optional, List, Dict, Any
from datetime import datetime
from sqlalchemy import and_, or_
from .models import CommodityHistoryData
from .sqlalchemy_database import SQLAlchemyDatabaseManager

class HistoryDataManager:
    def __init__(self):
        """
        初始化历史数据管理器
        """
        self.db = SQLAlchemyDatabaseManager()

    def batch_add_history_data(self, template_id: int, his_type: int, wear_value: float, trade_data_list: List[Dict]) -> bool:
        """
        批量添加历史数据
        :param template_id: 饰品ID
        :param his_type: 历史数据类型
        :param wear_value: 磨损值
        :param trade_data_list: 交易数据列表，每个元素包含time、price、localDate字段
        :return: 是否添加成功
        """
        session = self.db.get_session()
        try:
            # 获取当前时间
            current_time = datetime.now()
            
            # 批量创建历史数据记录
            history_records = []
            for trade_data in trade_data_list:
                # 检查是否已存在相同的记录
                existing_record = session.query(CommodityHistoryData).filter(
                    CommodityHistoryData.template_id == template_id,
                    CommodityHistoryData.his_type == his_type,
                    CommodityHistoryData.trade_time == trade_data['time']
                ).first()
                
                # 如果记录已存在，跳过
                if existing_record:
                    continue
                    
                # 创建新记录
                record = CommodityHistoryData(
                    template_id=template_id,
                    his_type=his_type,
                    wear_value=wear_value,
                    trade_time=trade_data['time'],
                    trade_date=datetime.strptime(trade_data['localDate'], '%Y-%m-%d').date(),
                    price=trade_data['price'],
                    create_time=current_time,
                    update_time=current_time
                )
                history_records.append(record)
            
            # 如果有新记录需要添加
            if history_records:
                session.bulk_save_objects(history_records)
                session.commit()
                
            return True
            
        except Exception as e:
            print(f"批量添加历史数据失败: {str(e)}")
            session.rollback()
            return False
            
        finally:
            session.close()

    def get_history_data(self, template_id: int, his_type: Optional[int] = None, 
                        start_date: Optional[str] = None, end_date: Optional[str] = None) -> List[Dict[str, Any]]:
        """
        获取历史数据
        :param template_id: 饰品ID
        :param his_type: 历史数据类型
        :param start_date: 开始日期，格式：YYYY-MM-DD
        :param end_date: 结束日期，格式：YYYY-MM-DD
        :return: 历史数据列表
        """
        session = self.db.get_session()
        try:
            query = session.query(CommodityHistoryData).filter(
                CommodityHistoryData.template_id == template_id
            )
            
            if his_type is not None:
                query = query.filter(CommodityHistoryData.his_type == his_type)
                
            if start_date:
                start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
                query = query.filter(CommodityHistoryData.trade_date >= start_date)
                
            if end_date:
                end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
                query = query.filter(CommodityHistoryData.trade_date <= end_date)
            
            # 按时间戳排序
            query = query.order_by(CommodityHistoryData.trade_time)
            
            records = query.all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()

    def delete_history_data(self, template_id: int, his_type: Optional[int] = None) -> bool:
        """
        删除历史数据
        :param template_id: 饰品ID
        :param his_type: 历史数据类型，如果不指定则删除该饰品的所有历史数据
        :return: 是否删除成功
        """
        session = self.db.get_session()
        try:
            query = session.query(CommodityHistoryData).filter(
                CommodityHistoryData.template_id == template_id
            )
            
            if his_type is not None:
                query = query.filter(CommodityHistoryData.his_type == his_type)
            
            query.delete()
            session.commit()
            return True
        except Exception as e:
            session.rollback()
            print(f"删除历史数据失败: {str(e)}")
            return False
        finally:
            session.close()

    def _convert_model_to_dict(self, model: CommodityHistoryData) -> Dict[str, Any]:
        """
        将模型对象转换为字典
        """
        if not model:
            return {}
            
        return {
            'id': model.id,
            'template_id': model.template_id,
            'his_type': model.his_type,
            'wear_value': float(model.wear_value),
            'trade_time': model.trade_time,
            'trade_date': model.trade_date.strftime('%Y-%m-%d'),
            'price': float(model.price),
            'create_time': model.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': model.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }
